import { ListView ,Flex,Modal,List,Toast,SegmentedControl,WingBlank} from 'antd-mobile';
import SVGIcon from '../../modules/svgIcon.jsx'
import './devOnline.css'

/* based svg-sprite-load 3.7 and webpack 4.8 */
import more from '../../font/svgs/more.svg'
import outdoorDevice from '../../font/svgs/outdoorDevice.svg'
import indoorDevice from '../../font/svgs/indoorDevice.svg'
class DevOnline extends React.Component{

    constructor(props){
        super(props);

        const getRowData = (dataBlob, sectionID,rowID) => {
            return dataBlob[sectionID][rowID]};

        this.state = {
            dataSource:new ListView.DataSource({
                getRowData,
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            modal:false,
            dialStr:'',
            loadingStr:'加载中...'
        }

        this.initPageParam();
        this.sIndex = 0;
        this.Index2DevType = {
            0 : "1", //门口机
            1 : "4", //室内机
            2 : "3", //围墙机
            3 : "2"  //管理机
        };
    }

    initPageParam(){
        this.page = 1;
        this.pageSize = 10;
        this.datas = [];
        this.initialized = false;
    }

    genRowKeys(data){
        for(let key in data)
            data[key].key = data[key].commCode;

        return data;
    }

    updateListData(end){
        initToken();
        let params = {
            page:this.page++,
            pageSize:this.pageSize,
            commCode:this.props.commCode,
            type:this.Index2DevType[this.sIndex]
        }
        postJson("/EquCtrl/queryEquList.x",params,(data)=>{
            this.initialized = true;
            if(data.list.length < this.pageSize || (data.list.length == 0 && end)) {
                this.pageSize = 0;
                this.setState({loadingStr:'已到最后'});
            }

            if(data.list.length == 0 && end)
                return;

            data.list = this.genRowKeys(data.list);

            this.datas.push.apply(this.datas,data.list);

            this.setState({
                dataSource:this.state.dataSource.cloneWithRows(this.datas)
            });
        });
    }

    componentDidMount(){
        this.updateListData(false);
    }

    onEndReached(){
        let loadingStr = '已到最后';
        if(this.pageSize == 0)
            this.setState({loadingStr:loadingStr});
        else{
            this.updateListData(true);
        }
    }

    moreClick(rowData){
        if(rowData.status === '1'){
            Toast.fail("设备不在线，无法操作");
            return;
        }
        this.rowDataSeleted = rowData;
        let dialStr = '';
        let upgrade = true;
        if(rowData.type === 4)
            dialStr = '呼叫室内机';
        else if(rowData.type === 1)
            dialStr = '监视梯口机';
        else if(rowData.type === 3)
            dialStr = '监视围墙机';
        else if(rowData.type === 2) {
            dialStr = '呼叫管理机';
            upgrade = false;
        }

        this.setState({modal:true,dialStr:dialStr,upgrade : upgrade});
    }

    closeModal(){
        this.setState({modal:false});
    }

    monitor(){
        nativeCall("appCall",this.rowDataSeleted.deviceNum);
    }

    upgrade(){
        let params = {};
        params.devicesNum = this.rowDataSeleted.deviceNum;
        postJson('/EquCtrl/updateApp.x', params, function (data) {
            Toast.info("升级消息已发送");
            this.setState({modal:false});
        })
    }

    typeOnchange(e){
        this.sIndex = e.nativeEvent.selectedSegmentIndex;
        this.initPageParam();
        this.updateListData(false);
    }

    render(){

        const separator = (rowID) => (
            <div
                key={`${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 8,
                    borderTop: '1px solid #ECECED',
                    borderBottom: '1px solid #ECECED',
                }}
            />
        );

        const row = (rowData,sectionID,rowID)=>{
            let fontColor = {};
            if(rowData.status == '1')
                fontColor = {color:'red'};
            else
                fontColor = {color:'green'};

            return (
                <div key={rowID} style={{ padding: '0 15px' }}>
                    <div className="row-header">
                        {rowData.buildingInfo?rowData.buildingInfo+" ":'' + rowData.deviceName}
                    </div>
                    <Flex  align="center" style={{padding:5}}>
                        <SVGIcon type={(rowData.type == 1?outdoorDevice.id:indoorDevice.id)} local="true" size="35" style={{marginRight:3}}/>

                        <div style={{marginLeft:10}}>
                            <div style={style.label}><span style={fontColor}>{rowData.status == '1'?'离线':'运行中'}</span></div>
                            <div style={style.label}>版本号 : {rowData.versionNumber}</div>
                            <div style={style.label}>时间 : {rowData.time}</div>
                        </div>
                        <Flex style={{flexGrow:1}} justify="end">
                            <SVGIcon type={more.id} local="true" size="lg" onClick={()=>this.moreClick(rowData)}/>
                        </Flex>
                    </Flex>
                </div>
            )
        }


        if(this.initialized && this.datas.length == 0){
            return (
                <div direction="column">
                    <SegmentedControl values={['门口机', '室内机','围墙机','管理机']} className="segment-top"
                                      onChange={(e)=>this.typeOnchange(e)} selectedIndex={this.sIndex}
                    />
                    <Flex direction="column" style={{padding: 30, textAlign: 'center'}}>
                        <img src="/pic/no_content.png" className="no-content-img" style={{width:200,height:200}}></img>
                        <span>没有任何设备在线</span>
                    </Flex>
                </div>
            )
        }else {
            return (
                <div direction="column">
                    <SegmentedControl values={['门口机', '室内机','围墙机','管理机']} className="segment-top"
                                      onChange={(e)=>this.typeOnchange(e)} selectedIndex={this.sIndex}
                    />
                    <ListView
                        dataSource={this.state.dataSource}
                        className="am-list sticky-list"
                        useBodyScroll
                        renderFooter={() => (<div style={{padding: 30, textAlign: 'center'}}>
                            {this.state.loadingStr}
                        </div>)}
                        renderRow={row}
                        renderSeparator={separator}
                        pageSize={4}
                        scrollEventThrottle={200}
                        onEndReached={() => this.onEndReached()}
                        onEndReachedThreshold={10}
                    />
                    <Modal
                        popup
                        visible={this.state.modal}
                        onClose={() => this.closeModal('modal')}
                        animationType="slide-up"
                    >
                        <List renderHeader={() => <div>操作</div>} className="popup-list">
                            <List.Item onClick={() => this.monitor()}>
                                {this.state.dialStr}
                            </List.Item>
                            <List.Item onClick={() => this.upgrade()} style={this.state.upgrade?{}:{display:"none"}}>
                                远程升级
                            </List.Item>
                        </List>
                    </Modal>
                </div>
            )
        }
    }
}

const style = {
    segment :{
      margin:2
    },
    label : {
        padding : 2,
        fontSize : 14
    }
};
ReactDOM.render( <DevOnline commCode={getUrlParam("commCode")}/>,document.getElementById("DevOnline"));